<?php
namespace app\common\exception;

use app\common\MyLog;
use think\exception\Handle;
use Exception;
use app\service\RecordLog;
use think\facade\Request;

/*
 * 重写Handle的render方法，实现自定义异常消息
 */
class ExceptionHandler extends Handle {
    private $code;
    private $msg;
    private $error_code;
    private $content;
    private $request_url;
    private $log_id;

    public function render(Exception $e) {
        if ($e instanceof BaseException) {
            //如果是自定义异常，则控制http状态码，不需要记录日志
            //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常 不应当记录日志

            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->error_code = $e->error_code;
            $this->content = is_object($e->content) ? $e->content->toArray() : $e->content;
            $this->request_url = $e->request_url;
            $this->log_id = $e->log_id;
            MyLog::infoLog('[debug]',' [Request]:'. json_encode(Request::param(),true) . ' [Content]:'. json_encode($this->content,true). ' [Msg]:'.$this->msg,'api');
        } else{
            // 如果是服务器未处理的异常，将http状态码设置为500，并记录日志
            if(config('app_debug')){
                return parent::render($e);
            }

            $this->code = 500;
            $this->msg = 'sorry，这是一个未知错误. (^o^)Y';
            $this->error_code = 999;
            $this->log_id = MyLog::setLogId();
            $this->recordErrorLog($e);
        }
        
        $result = [
            'msg'  => $this->msg.'。小福利：https://item.jd.com/13443805.html',
            'error_code' => $this->error_code,
            'content' => $this->content,
            'log_id' => $this->log_id,
        ];
        return json($result, $this->code);
    }

    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Exception $e) {
        $content = '';
        $content .= "\r\n log_id:".$this->log_id;
        $content .= "\r\n file:".$e->getFile();
        $content .= "\r\n request params:".json_encode(Request::param(),true);
        $content .= "\r\n line:".$e->getLine();
        $content .= "\r\n msg:".$e->getMessage();
        MyLog::errorLog('[error]','[File]:' . $e->getFile() . ' [Line]:'. $e->getLine() . ' [Request]:'. json_encode(Request::param(),true) .' [Msg]:' .$e->getMessage(),'api');
        RecordLog::recordLog($content, 'error', true);
    }
}